<script lang="ts" setup>
import { uploadAPI } from "@/apis/common";
import {
  createRentAPI,
  delEnterpriseAPI,
  deleteRentAPI,
  getEnterpriseListAPI,
  getRentBuildListAPI,
  getRentListAPI,
  outRentAPI,
} from "@/apis/enterprise";
import {
  type Datum,
  type Enterprise,
  type EnterpriseListParams,
  type RentBuilding,
  type RentParams,
} from "@/types/enterprise";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
import { onMounted, ref, watch } from "vue";

const list = ref<Enterprise[]>([]);
const total = ref(0);
const params = ref<EnterpriseListParams>({
  name: "",
  page: 1,
  pageSize: 10,
});
const getList = async () => {
  const res = await getEnterpriseListAPI(params.value);
  console.log(res.data.rows);
  list.value = res.data.rows;
  total.value = res.data.total;
};
onMounted(() => {
  getList();
});
const onSearch = () => {
  params.value.page = 1;
  getList();
  console.log(params.value);
};
const onDelete = (id: string) => {
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await delEnterpriseAPI(id);
      ElMessage.success("删除成功");
      getList();
      console.log(res);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
const rentDialogVisible = ref(false);
const addRent = async (id: number) => {
  rentDialogVisible.value = true;
  const res = await getRentBuildListAPI();
  console.log("addRent", res);
  buildList.value = res.data;
  rentForm.value.enterpriseId = id;
};
const closeDialog = () => {
  rentDialogVisible.value = false;
  addFormRef.value?.resetFields();
  timeArr.value.length = 0;
  rentForm.value = {
    buildingId: undefined,
    startTime: "",
    endTime: "",
    contractUrl: "",
    enterpriseId: undefined,
    type: 0,
    contractId: undefined,
  };
  fileList.value.length = 0;
};
const rentForm = ref<RentParams>({
  buildingId: undefined, // 租赁楼宇id
  startTime: "", // 开始日期（不能小于今日日期）
  endTime: "", // 租赁结束日期
  contractUrl: "", // 合同附件url
  contractId: 0, // 合同附件id
  type: 0, // 操作类型，添加合同0，续签合同1
  enterpriseId: 0, // 企业id
});
const rentRules = ref<FormRules<RentParams>>({
  buildingId: [{ required: true, message: "请选择楼宇", trigger: "change" }],
  endTime: [{ required: true, message: "请选择租赁日期", trigger: "blur" }],
  contractUrl: [{ required: true, message: "请上传合同文件", trigger: "blur" }],
});
const addFormRef = ref<FormInstance>();
const buildList = ref<RentBuilding[]>([]);
const timeArr = ref<string[]>([]);
watch(
  timeArr,
  (val) => {
    if (val) {
      rentForm.value.startTime = val[0];
      rentForm.value.endTime = val[1];
    } else {
      rentForm.value.startTime = "";
      rentForm.value.endTime = "";
    }
  },
  { deep: true }
);
const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};
const onUploadRequest = async (options: UploadRequestOptions) => {
  const fd = new FormData();
  fd.append("file", options.file);
  fd.append("type", "contract");
  const res = await uploadAPI(fd);
  console.log(res);
  rentForm.value.contractId = res.data.id;
  rentForm.value.contractUrl = res.data.url;
  addFormRef.value?.validateField("contractId");
};
const fileList = ref<UploadUserFile[]>([]);
const beforeUpload = (rawFile: UploadRawFile) => {
  const allowSize = 5 * 1024 * 1024;
  if (rawFile.size > allowSize) {
    ElMessage.warning("文件过大，请上传小于5M的文件");
    return false;
  }
  return true;
};
const removeUpload = () => {
  rentForm.value.contractUrl = "";
  rentForm.value.contractId = undefined;
  addFormRef.value?.validateField("contractUrl");
};
const addRentConfirm = async () => {
  try {
    await addFormRef.value?.validate();
    await createRentAPI(rentForm.value);
    ElMessage.success("添加成功");
    rentDialogVisible.value = false;
  } catch {}
};
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList: Datum[];
}
const exterpriseList = ref<EnterpriseWithRent[]>([]);
const getExterpriseList = async () => {
  const res = await getEnterpriseListAPI(params.value);
  exterpriseList.value = res.data.rows.map((item) => ({
    ...item,
    rentList: [],
  }));
};
getExterpriseList();
const gentRentList = async (row: EnterpriseWithRent) => {
  const res = await getRentListAPI(row.id);

  row.rentList = res.data;
};
const outRent = (row: Datum) => {
  ElMessageBox.confirm("退租操作不可撤回,是否确认退租当前楼宇？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await outRentAPI(row.id);
    row.status = 3;
    ElMessage.success("退租成功");
  });
};
const deleteRent = (rentRow: Datum, fatherRow: EnterpriseWithRent) => {
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteRentAPI(rentRow.id);
    fatherRow.rentList = fatherRow.rentList.filter(
      (item) => item.id !== rentRow.id
    );
    ElMessage.success("删除成功");
  });
};
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model:model-value="params.name"
        @clear="onSearch"
      />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="exterpriseList"
        @expand-change="gentRentList"
        row-key="id"
      >
        <el-table-column type="expand">
          <template v-slot="{ row: fatherRow }">
            <el-table :data="fatherRow.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template v-slot="{ row }">
                  <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
                  <el-tag v-else-if="row.status === 1" type="success"
                    >生效中</el-tag
                  >
                  <el-tag v-else-if="row.status === 2" type="info"
                    >已到期</el-tag
                  >
                  <el-tag v-else-if="row.status === 3" type="danger"
                    >已退租</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template v-slot="{ row: rentRow }">
                  <el-button size="small" type="text">续租</el-button>
                  <el-button size="small" type="text" :disabled="rentRow.status === 3" @click="outRent(rentRow)">退租</el-button>
                  <el-button size="small" type="text" :disabled="rentRow.status !== 3" @click="deleteRent(rentRow,fatherRow)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="contact" />
        <el-table-column label="联系人" prop="name" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="text" @click="addRent(row.id)"
              >添加合同</el-button
            >
            <el-button size="small" type="text" @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button
              size="small"
              type="text"
              @click="$router.push(`/exterpriseAdd/${row.id}`)"
              >编辑</el-button
            >
            <el-button size="small" type="text" @click="onDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="total"
        layout="total, prev, pager, next,sizes,jumper"
        :page-sizes="[2, 5, 10, 20, 100]"
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList"
      />
    </div>
    <el-dialog
      title="添加合同"
      v-model="rentDialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <div class="form-container">
        <el-form
          ref="addFormRef"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker
              v-model="timeArr"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              accept=".doc, .pdf"
              :http-request="onUploadRequest"
              @remove="removeUpload"
              :before-upload="beforeUpload"
              v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名：.doc .pdf, 文件大小不超过5M
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        {{ rentForm }}
        {{ timeArr }}
      </div>
      <template #footer>
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addRentConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
  {{ params }}
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
